﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Nox.Amuse.MVVM;
using Nox.Amuse.Model;
using System.Reflection;
using Nox.Amuse.ViewModel;
using Nox.Amuse.Helpers;

namespace Nox.Amuse
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        // Backing store for Messenger
        readonly static Messenger myMessenger = new Messenger();

        // Gets the internal Application Communication System
        internal static Messenger Messenger
        {
            get { return myMessenger; }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            App.Messenger.Register(Messages.ExitRequest, () => { HandleExitRequest(); });
            bool isTestMode = e.Args.Any((a) =>
            {
                return a == @"/testupdate" ? true : false;
            });

            UpdateViewModel.Initialize(isTestMode);

            this.MainWindow = new MainWindow();
            this.MainWindow.Show();
            // If the window was saved in a minimised state, this will restore the window
            if (this.MainWindow.WindowState == WindowState.Minimized)
                this.MainWindow.WindowState = WindowState.Normal;

            // Must be done after or dialog gets eatten
            if (UpdateViewModel.CurrentUpdateViewModel.IsFirstRunPostUpdate)
            {
                MessageBox.Show("Amuse has been successfully updated", "Placeholder Alert", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            App.Messenger.NotifyColleagues(Messages.Exiting);
        }

        public static bool IsReadyToExit = false;

        private void HandleExitRequest()
        {
            if (System.Windows.MessageBox.Show(
                            "Exit Amuse?",
                            "Placeholder Alert",
                            System.Windows.MessageBoxButton.YesNo,
                            System.Windows.MessageBoxImage.None,
                            System.Windows.MessageBoxResult.No) == System.Windows.MessageBoxResult.Yes)
                IsReadyToExit = true;
            else
                IsReadyToExit = false;
        }

    }
}
